package com.fr.base.dav;

import com.fr.base.FRContext;
import com.fr.base.Inter;
import com.fr.base.XMLFileManager;
import com.fr.base.XMLTools;
import com.fr.base.core.BaseCoreUtils;
import com.fr.base.core.ComparatorUtils;
import com.fr.base.xml.XMLPrintWriter;
import com.fr.base.xml.XMLableReader;
import com.fr.data.TableData;
import com.fr.data.TableDataException;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.TableProcedure;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import com.fr.data.impl.DatabaseConnection;
import com.fr.data.impl.EmbeddedTableData;
import com.fr.report.RWorkBook;
import com.fr.report.ResultWorkBook;
import com.fr.report.TemplateWorkBook;
import com.fr.report.WorkBook;
import com.fr.report.io.TemplateExporter;
import com.fr.report.io.TemplateImporter;
import com.fr.report.parameter.Parameter;
import com.fr.util.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LocalEnv
  implements Env
{
  private String path;
  private Map tableDataMap = new HashMap();

  public LocalEnv()
  {
  }

  public LocalEnv(String paramString)
  {
    this.path = paramString;
  }

  public String getPath()
  {
    return this.path;
  }

  public void checkValid()
    throws EnvException
  {
    File localFile = new File(this.path);
    if (!(localFile.isDirectory()))
      throw new EnvException(this.path + " is not a valid directory.");
    if (!(ComparatorUtils.equals(localFile.getName(), "WEB-INF")))
      throw new EnvException(Inter.getLocText("Env-Des1"));
  }

  public InputStream readResource(String paramString)
    throws Exception
  {
    return new FileInputStream(BaseCoreUtils.pathJoin(new String[] { this.path, "resources", paramString }));
  }

  public boolean writeResource(XMLFileManager paramXMLFileManager)
    throws Exception
  {
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, "resources", paramXMLFileManager.fileName() }));
    Utils.mkfile(localFile);
    FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
    XMLTools.writeOutputStreamXML(paramXMLFileManager, localFileOutputStream);
    localFileOutputStream.close();
    return true;
  }

  public boolean isTemplateExist(String paramString)
    throws Exception
  {
    if (paramString == null)
      return false;
    return new File(BaseCoreUtils.pathJoin(new String[] { this.path, "reportlets", paramString })).exists();
  }

  public TemplateWorkBook readTemplate(String paramString)
    throws Exception
  {
    WorkBook localWorkBook = null;
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, "reportlets", paramString }));
    if (localFile.exists())
    {
      TemplateImporter localTemplateImporter = new TemplateImporter();
      localWorkBook = localTemplateImporter.generateTemplate(localFile);
    }
    else
    {
      throw new FileNotFoundException(Inter.getLocText("Cannot_Found_Template_File") + ":" + paramString);
    }
    return localWorkBook;
  }

  public boolean writeTemplate(TemplateWorkBook paramTemplateWorkBook, String paramString)
    throws Exception
  {
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, "reportlets", paramString }));
    if (!(localFile.exists()))
      Utils.mkfile(localFile);
    FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
    new TemplateExporter().export(localFileOutputStream, paramTemplateWorkBook);
    localFileOutputStream.flush();
    localFileOutputStream.close();
    return true;
  }

  public boolean createFolder(String paramString)
  {
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, paramString }));
    if (localFile.exists())
      return true;
    return Utils.mkdirs(localFile);
  }

  public boolean createFile(String paramString)
    throws Exception
  {
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, paramString }));
    if (localFile.exists())
      return true;
    return Utils.mkfile(localFile);
  }

  public boolean fileExists(String paramString)
  {
    return new File(BaseCoreUtils.pathJoin(new String[] { this.path, paramString })).exists();
  }

  public InputStream fileInputStream(String paramString)
    throws Exception
  {
    return new FileInputStream(BaseCoreUtils.pathJoin(new String[] { this.path, paramString }));
  }

  public FileNode[] listFile(String paramString)
  {
    ArrayList localArrayList = new ArrayList();
    File localFile1 = new File(BaseCoreUtils.pathJoin(new String[] { this.path, paramString }));
    if (localFile1.isFile())
    {
      localArrayList.add(new FileNode(paramString, localFile1.isDirectory()));
    }
    else
    {
      File[] arrayOfFile = localFile1.listFiles();
      int i = 0;
      int j = (arrayOfFile == null) ? 0 : arrayOfFile.length;
      while (i < j)
      {
        File localFile2 = arrayOfFile[i];
        localArrayList.add(new FileNode(BaseCoreUtils.pathJoin(new String[] { paramString, localFile2.getName() }), localFile2.isDirectory()));
        ++i;
      }
    }
    return ((FileNode[])localArrayList.toArray(new FileNode[localArrayList.size()]));
  }

  public boolean testConnection(DatabaseConnection paramDatabaseConnection)
  {
    if (paramDatabaseConnection == null)
      return false;
    try
    {
      paramDatabaseConnection.testConnection();
    }
    catch (Exception localException)
    {
      FRContext.getLogger().log(Level.SEVERE, localException.getMessage(), localException);
      return false;
    }
    return true;
  }

  public List getTableColumnNames(TableData paramTableData)
    throws Exception
  {
    List localList = (List)this.tableDataMap.get(paramTableData);
    return localList;
  }

  public void setTableColumnNames(TableData paramTableData)
    throws Exception
  {
    ArrayList localArrayList = new ArrayList();
    TableData localTableData = null;
    try
    {
      localTableData = FRContext.getCurrentEnv().previewTableData(paramTableData, Collections.EMPTY_MAP, 0);
    }
    catch (Exception localException1)
    {
      FRContext.getLogger().log(Level.WARNING, localException1.getMessage(), localException1);
    }
    if (localTableData != null)
    {
      int j;
      try
      {
        int i = localTableData.getColumnCount();
        for (j = 0; j < i; ++j)
        {
          String str = localTableData.getColumnName(j);
          localArrayList.add(str);
        }
      }
      catch (TableDataException localTableDataException)
      {
        FRContext.getLogger().log(Level.WARNING, localTableDataException.getMessage(), localTableDataException);
      }
      try
      {
        localTableData.release();
      }
      catch (Exception localException2)
      {
        FRContext.getLogger().log(Level.WARNING, localException2.getMessage(), localException2);
      }
    }
    Collections.sort(localArrayList);
    this.tableDataMap.put(paramTableData, localArrayList);
  }

  public String[] getTableSchema(DatabaseConnection paramDatabaseConnection)
    throws Exception
  {
    if (paramDatabaseConnection == null)
      return null;
    Connection localConnection = paramDatabaseConnection.createConnection();
    if (localConnection == null)
      throw new Exception("Cannot connect to database!");
    Dialect localDialect = DialectFactory.generateDialect(localConnection);
    try
    {
      String[] arrayOfString = localDialect.getSchemas(localConnection);
      return arrayOfString;
    }
    finally
    {
      if (localConnection != null)
        DBUtils.closeConnection(localConnection);
    }
  }

  public TableProcedure[] getSQLTablesProcedure(DatabaseConnection paramDatabaseConnection, String paramString)
    throws Exception
  {
    Object localObject1 = new ArrayList();
    ResultSet localResultSet = null;
    String str1 = null;
    Connection localConnection = paramDatabaseConnection.createConnection();
    if (localConnection == null)
      throw new Exception("Cannot connect to database!");
    if (paramString != null)
      str1 = localConnection.getCatalog();
    Dialect localDialect = DialectFactory.generateDialect(localConnection);
    localObject1 = localDialect.getTableProcedure(localConnection, paramString, false);
    DatabaseMetaData localDatabaseMetaData = localConnection.getMetaData();
    String[] arrayOfString = { "VIEW" };
    try
    {
      localResultSet = localDatabaseMetaData.getTables(str1, paramString, "%", arrayOfString);
    }
    catch (SQLException localSQLException1)
    {
      localResultSet = localDatabaseMetaData.getTables(str1, paramString, "%", arrayOfString);
    }
    while (localResultSet.next())
      ((List)localObject1).add(new TableProcedure(localResultSet.getString(2), localResultSet.getString(3), localResultSet.getString(4)));
    localResultSet.close();
    try
    {
      localResultSet = localDatabaseMetaData.getProcedures(str1, paramString, "%");
      while (localResultSet.next())
      {
        String str2 = localResultSet.getString(3);
        int i = str2.lastIndexOf(";");
        if (i > 0)
          str2 = str2.substring(0, i);
        ((List)localObject1).add(new TableProcedure(localResultSet.getString(2), str2, "PROCEDURE"));
      }
      localResultSet.close();
    }
    catch (SQLException localSQLException2)
    {
      FRContext.getLogger().log(Level.SEVERE, localSQLException2.getMessage(), localSQLException2);
    }
    finally
    {
      if (localConnection != null)
        localConnection.close();
    }
    return ((TableProcedure)(TableProcedure[])((List)localObject1).toArray(new TableProcedure[((List)localObject1).size()]));
  }

  public TableProcedure[] getTableProcedure(DatabaseConnection paramDatabaseConnection, String paramString1, String paramString2)
    throws Exception
  {
    Object localObject1;
    Object localObject2;
    TableProcedure[] arrayOfTableProcedure = null;
    ResultSet localResultSet = null;
    String str = null;
    Connection localConnection = paramDatabaseConnection.createConnection();
    if (localConnection == null)
      throw new Exception("Cannot connect to database!");
    if (paramString2 != null)
      str = localConnection.getCatalog();
    if (paramString1.equals("TABLE"))
    {
      localObject1 = new ArrayList();
      localObject2 = DialectFactory.generateDialect(localConnection);
      localObject1 = ((Dialect)localObject2).getTableProcedure(localConnection, paramString2, false);
      arrayOfTableProcedure = (TableProcedure[])((List)localObject1).toArray(new TableProcedure[((List)localObject1).size()]);
    }
    else
    {
      Object localObject3;
      if (paramString1.equals("VIEW"))
      {
        localObject1 = new ArrayList();
        localObject2 = localConnection.getMetaData();
        localObject3 = new String[] { "VIEW" };
        try
        {
          localResultSet = ((DatabaseMetaData)localObject2).getTables(str, paramString2, "%", localObject3);
        }
        catch (SQLException localSQLException2)
        {
          localResultSet = ((DatabaseMetaData)localObject2).getTables(str, paramString2, "%", localObject3);
        }
        while (localResultSet.next())
          ((List)localObject1).add(new TableProcedure(localResultSet.getString(2), localResultSet.getString(3), localResultSet.getString(4)));
        localResultSet.close();
        arrayOfTableProcedure = (TableProcedure[])((List)localObject1).toArray(new TableProcedure[((List)localObject1).size()]);
      }
      else if (paramString1.equals("PROCEDURE"))
      {
        localObject1 = new ArrayList();
        try
        {
          localObject2 = localConnection.getMetaData();
          localResultSet = ((DatabaseMetaData)localObject2).getProcedures(str, paramString2, "%");
          while (localResultSet.next())
          {
            localObject3 = localResultSet.getString(3);
            int i = ((String)localObject3).lastIndexOf(";");
            if (i > 0)
              localObject3 = ((String)localObject3).substring(0, i);
            ((List)localObject1).add(new TableProcedure(localResultSet.getString(2), (String)localObject3, "PROCEDURE"));
          }
          localResultSet.close();
        }
        catch (SQLException localSQLException1)
        {
          FRContext.getLogger().log(Level.SEVERE, localSQLException1.getMessage(), localSQLException1);
        }
        arrayOfTableProcedure = (TableProcedure[])((List)localObject1).toArray(new TableProcedure[((List)localObject1).size()]);
      }
      else if (paramString1.equals("ALLTABLE"))
      {
        localObject1 = new ArrayList();
        Dialect localDialect = DialectFactory.generateDialect(localConnection);
        localObject1 = localDialect.getTableProcedure(localConnection, paramString2, true);
        arrayOfTableProcedure = (TableProcedure[])((List)localObject1).toArray(new TableProcedure[((List)localObject1).size()]);
      }
    }
    if (localConnection != null)
      localConnection.close();
    return ((TableProcedure)(TableProcedure)(TableProcedure)arrayOfTableProcedure);
  }

  public Parameter[] getTableDataParameters(TableData paramTableData)
  {
    Parameter[] arrayOfParameter = null;
    if (paramTableData != null)
      arrayOfParameter = paramTableData.getParameters();
    return ((arrayOfParameter == null) ? new Parameter[0] : arrayOfParameter);
  }

  public TableData previewTableData(TableData paramTableData, Map paramMap, int paramInt)
    throws TableDataException
  {
    TableData localTableData = null;
    EmbeddedTableData localEmbeddedTableData = null;
    try
    {
      localTableData = (TableData)paramTableData.clone();
    }
    catch (CloneNotSupportedException localCloneNotSupportedException)
    {
      FRContext.getLogger().log(Level.WARNING, localCloneNotSupportedException.getMessage(), localCloneNotSupportedException);
    }
    Parameter[] arrayOfParameter = localTableData.getParameters();
    int i = 0;
    int j = (arrayOfParameter == null) ? 0 : arrayOfParameter.length;
    while (i < j)
    {
      Object localObject1 = paramMap.get(arrayOfParameter[i].getName());
      if (localObject1 != null)
        arrayOfParameter[i].setValue(localObject1);
      ++i;
    }
    try
    {
      localEmbeddedTableData = EmbeddedTableData.embedify(localTableData, paramInt);
    }
    catch (TableDataException localTableDataException)
    {
    }
    finally
    {
      try
      {
        localTableData.release();
      }
      catch (Exception localException)
      {
        FRContext.getLogger().log(Level.WARNING, localException.getMessage(), localException);
      }
    }
    return ((localEmbeddedTableData == null) ? new EmbeddedTableData() : localEmbeddedTableData);
  }

  public Parameter[] getTemplateParameters(TemplateWorkBook paramTemplateWorkBook)
    throws Exception
  {
    if (paramTemplateWorkBook == null)
      return new Parameter[0];
    Parameter[] arrayOfParameter = paramTemplateWorkBook.getParameters();
    return ((arrayOfParameter == null) ? new Parameter[0] : arrayOfParameter);
  }

  public ResultWorkBook executeTemplate(TemplateWorkBook paramTemplateWorkBook, Map paramMap)
  {
    return paramTemplateWorkBook.execute(paramMap);
  }

  public void openContainerFolder(FileNode paramFileNode)
  {
    if (paramFileNode == null)
      return;
    Utils.openWindowsFolder(BaseCoreUtils.pathJoin(new String[] { this.path, paramFileNode.getEnvPath() }));
  }

  public void readXML(XMLableReader paramXMLableReader)
  {
    if ((paramXMLableReader.isChildNode()) && ("DIR".equals(paramXMLableReader.getTagName())))
      this.path = paramXMLableReader.getElementValue();
  }

  public void writeXML(XMLPrintWriter paramXMLPrintWriter)
  {
    paramXMLPrintWriter.startTAG("DIR").textNode(this.path).end();
  }

  public boolean writeResult(ResultWorkBook paramResultWorkBook, String paramString)
    throws Exception
  {
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, "resultlets", paramString }));
    if (!(localFile.exists()))
      Utils.mkfile(localFile);
    localFile.getAbsolutePath();
    FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
    new TemplateExporter().export(localFileOutputStream, paramResultWorkBook);
    localFileOutputStream.flush();
    localFileOutputStream.close();
    return true;
  }

  public ResultWorkBook readResult(String paramString)
    throws Exception
  {
    if (paramString == null)
      return null;
    RWorkBook localRWorkBook = null;
    File localFile = new File(BaseCoreUtils.pathJoin(new String[] { this.path, "resultlets", paramString }));
    if (localFile.exists())
    {
      TemplateImporter localTemplateImporter = new TemplateImporter();
      localRWorkBook = localTemplateImporter.generateResult(localFile);
    }
    else
    {
      throw new FileNotFoundException(Inter.getLocText("Cannot_Found_Result_File") + ":" + paramString);
    }
    return localRWorkBook;
  }
}